package org.anyline.simple.es;

import org.anyline.data.elasticsearch.entity.ElasticSearchRow;
import org.anyline.data.elasticsearch.param.ElasticSearchConfigStore;
import org.anyline.entity.DataRow;
import org.anyline.entity.DataSet;
import org.anyline.metadata.Table;
import org.anyline.proxy.ServiceProxy;
import org.anyline.util.BasicUtil;
import org.anyline.util.ConfigTable;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.List;

@SpringBootTest
public class VectorTest {
    public static Logger log = LoggerFactory.getLogger(VectorTest.class);
    public static String table_name = "es_index_table";
    @Test
    public void vector() throws Exception{
        ConfigTable.IS_PRINT_EXCEPTION_STACK_TRACE = true;
        Table table = ServiceProxy.metadata().table("es_index_vector");
        if(null != table){
            ServiceProxy.ddl().drop(table);
        }
        //简单的索引，只有列的话 可以通过普通的Table创建
        table = new Table("es_index_vector");
        table.addColumn("id"            	, "integer"     ).setStore(true);   // 业务主键
        table.addColumn("title"            	, "text"     ).setStore(true);  // 标题
        table.addColumn("spec"        	, "dense_vector"     )
            .setStore(true)
            .setSimilarity("l2_norm") //相似度算法 如 l2_norm dot_product cosine max_inner_product
            .setDims(5);  // 维度dims 可以通过Precision或Length设置

        ServiceProxy.ddl().create(table);
        //插入一部分测试数据

        DataSet set = new DataSet();
        long fr = System.currentTimeMillis();
        for(int i=0; i<10; i++){
            DataRow row = new ElasticSearchRow();
            set.add(row);
            row.put("id", i);
            row.put("title", "title"+i);
            List<Double> spec = new ArrayList<>();
            for(int c=0; c<5; c++){
                spec.add(BasicUtil.getRandomNumber(0d,1d));
            }
            row.put("spec", spec);
        }
        ServiceProxy.insert("es_index_vector", set);
        set = ServiceProxy.querys("es_index_vector");
        System.out.println(set.getJson());


    }
    @Test
    public void vector_query() throws Exception{
        //通用查询条件
        ElasticSearchConfigStore configs = new ElasticSearchConfigStore();
        List<Double> spec = new ArrayList<>();
        for(int c=0; c<5; c++){
            spec.add(BasicUtil.getRandomNumber(0d,1d));
        }
        configs.match("spec", spec);
        configs.match("title", "实时");

        DataSet set = ServiceProxy.querys(table_name, configs);
        System.out.println(set.getJson());
    }
}
